import Vue from 'vue'
import VueI18n from 'vue-i18n'
import axios from "axios";

import ElementLocale from 'element-ui/lib/locale'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'

import langZh from "@/language/config/cn.js"
import langEN from "@/language/config/en.js"
import langko from "@/language/config/ko.js"
import http from '@/http';

Vue.use(VueI18n)

// const i18n = new VueI18n({
//   locale: 'zh',
//   messages: {
//     'zh': {
//       ...langZh,
//       ...zhLocale
//     },
//     'en': {
//       ...langEN,
//       ...enLocale
//     },
//      'ko': {
//        ...langko,
//        ...enLocale
//      }
//   }
// })
// ElementLocale.i18n((key, value) => i18n.t(key, value))

// export default i18n

// 上述注释方法为本地语言调用方式    下方为后端返回上方对应语言格式的配置   可自由选择方法

const i18n = new VueI18n({
    locale: 'zh',
    fallbackLocale: 'zh',
    silentTranslationWarn: true,  //去除i8n警告
})
export default i18n

const loadedLanguages = []

function setI18nLanguage(lang) {
    i18n.locale = lang
    axios.defaults.headers.common['Accept-Language'] = lang
    document.querySelector('html').setAttribute('lang', lang)
    return lang
}

export function loadLanguageAsync(lang) {
    if (loadedLanguages.includes(lang)) {
        if (i18n.locale !== lang) setI18nLanguage(lang)
        return Promise.resolve()
    }
    return http.i18nAPI().then(response => {
        let msgs = response.data
        for (const lang in msgs) {
            loadedLanguages.push(lang)
            i18n.setLocaleMessage(lang, msgs[lang])
        }
        // ElementLocale.i18n((key, value) => i18n.t(key, value))
    })
}
